///用于计算工程部工单评价分数 (不包括经销商的工单){ 代理安装工单|| 服务工单 || 保养工单 }
public without sharing class WorkOrderPerformanceController {
    
    public String woId {get;set;}
    public WorkOrder__c wo {get;set;}
    public List<WorkOrderTeam__c> woTeams {get;set;}

    public String msg {get;set;}
    public Boolean isSuccess {get;set;}
    public Boolean isErr {get;set;}

    public User u ;

    public WorkOrderPerformanceController() {

        woId =System.currentPageReference().getParameters().get('id');

    	woTeams = new List<WorkOrderTeam__c>();
    	
    	wo = new WorkOrder__c();

    	u = [select Id, Profile.Name,WorkOrderRater__c from User where Id=:UserInfo.getUserId()];

    }
    public void init(){

    	System.debug('===='+ woId);


        try {
            if(woId == null)throw new DmlException('页面打开错误!');

            if( !u.WorkOrderRater__c  && ( u.Profile.Name != '工程部主管' && u.Profile.Name != '工程部组长' 
                &&u.Profile.Name != '工程部专家组' && u.Profile.Name != '系统管理员'))throw new DmlException('您没有权限评分!');
            


            wo = [select RecordType.DeveloperName,Id,InstrumentType__c,ModuleNumber__c,PerformanceComments__c,Teaching__c,BeentoughtEngineer__c,
            ProjectPerformanceScore__c, EvaluateServiceType__c, Status__c ,ProductLine__c,Subtraction__c , Case__r.Status,
            Case__r.RecordType.DeveloperName from WorkOrder__c where Id =:woId];
            System.Debug(wo);
            
            if(wo == null ) throw new DmlException('页面打开错误!');
                 

             woTeams = [select Id, User__c,User__r.Name  ,IsSupport__c ,SynergeticPerformanceScore__c from WorkOrderTeam__c where WorkOrder__c =:wo.Id];

            System.debug(woTeams);
            if(wo.RecordType.DeveloperName != 'NonAgentInstallationOrder' 
                && wo.RecordType.DeveloperName != 'InstallationOrder' 
                && wo.RecordType.DeveloperName != 'ServiceOrder' 
                && wo.RecordType.DeveloperName != 'MaintenanceOrder'
                && wo.RecordType.DeveloperName !='CalibrationEngineer'
                && wo.RecordType.DeveloperName !='Upgrade'
                && wo.RecordType.DeveloperName !='Relocation')throw new DmlException('此类工单不能进行工单绩效评分!');
            if(wo.Case__r.Status != '关闭')throw new DmlException('服务请求关闭才能进行工单绩效评分!');

           
        }
        catch (Exception e) {
            isErr = true;
            ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
        }
        
    	

    }

    
    public void save(){

    	msg = '';
    	Decimal score = null; //总分
    	Decimal x = wo.ModuleNumber__c;//模块数
    	Decimal y = wo.Subtraction__c == null ? 0 : wo.Subtraction__c ;//减分项

       // System.debug('WorkOrderPerformanceController==>'+ wo.ProductLine__c );
    	if(wo.EvaluateServiceType__c == '安装/移机'){

    		if(wo.ProductLine__c == '生化' || wo.ProductLine__c == '免疫' ){

	    		score =  wo.InstrumentType__c == '单机'  ? 15 : (3 + x) * 5;

	    	}else if(wo.ProductLine__c == '临检' || wo.ProductLine__c == '微生物'){

	    		score =  wo.InstrumentType__c == '单机'  ? 10 : (3 + x) * 5;

	    	}else{
	    		score = 5;
	    	}

    	}else if(wo.EvaluateServiceType__c == '保养'){

    		if(wo.ProductLine__c == '生化' || wo.ProductLine__c == '免疫' ){

	    		score =  wo.InstrumentType__c == '单机'  ? 4 : x * 4;

	    	}else if(wo.ProductLine__c == '临检' || wo.ProductLine__c == '微生物'){

	    		score =  wo.InstrumentType__c == '单机'  ? 2 : x * 2;

	    	}else{

	    		score = 2;

	    	}

    	}else if(wo.EvaluateServiceType__c == '服务'){

	    	score =  wo.ProductLine__c == '生化'  ? 10 : 5 ;

    	}else if(wo.EvaluateServiceType__c == '校准'){

    		if(wo.ProductLine__c == '生化' || wo.ProductLine__c == '免疫' ){

	    		score =  wo.InstrumentType__c == '单机'  ? 10 : x * 10;

	    	}else if(wo.ProductLine__c == '临检' ){

	    		score =  wo.InstrumentType__c == '单机'  ? 5 : x * 5;

	    	}else{
	    		score = 5;
	    	}

    	}
    	score = score - y;
        Decimal rito = wo.Teaching__c ? 1.5 : 1;
        
        score =  score  * rito ;
    	wo.ProjectPerformanceScore__c = score  ;

        System.debug('WorkOrderPerformanceController==>1 '+ woTeams.size());

    	if(woTeams.size() > 0){
    		Map<String,List<WorkOrderTeam__c>> tMap = new Map<String,List<WorkOrderTeam__c>>();
	    	for (WorkOrderTeam__c wt :woTeams ) {
	    		
                addMeta(tMap,wt.IsSupport__c ?'true' :'false',wt);
	    	}
	    	System.debug('==>'+ tMap);

	    	Integer  fs = tMap.get('false') == null ? 0 : tMap.get('false').size();//协同小组未支援人数

	    	Integer ts = tMap.get('true') == null ? 0 : tMap.get('true').size();//协同小组支援人数

	    	Boolean isSupport = ts  == 0 ? false : true ;

	    	Decimal s1 = ts  == 0 ? 0 : score * 0.75 / ts; //支援人评分

	    	Decimal s2 = isSupport ? ( score * 0.25 / (fs + 1)) : score / (fs + 1)  ;//未支援人评分

	    	wo.EngineerPerformanceScore__c = s2 ;//工程师绩效评分

	    	for (WorkOrderTeam__c wt :woTeams ) {
	    		wt.SynergeticPerformanceScore__c =  wt.IsSupport__c == true ? s1 : s2 ;//协同评分
	    	}


    	}
        if(woTeams.isEmpty()) wo.EngineerPerformanceScore__c = score;


    	SavePoint sp = Database.setSavepoint();
    	try {
    	    update woTeams;
            wo.Finalmodificationtime__c = System.now();
            wo.Raters__c = UserInfo.getName();
    		update wo ;
    		isSuccess = true;
    		msg = '保存成功!';
            if(System.test.isRunningTest() )throw new DmlException('test');
    	}
    	catch (Exception e) {
    		isSuccess = false;
    		msg = '保存失败!'+e.getMessage();
    	 	 Database.rollback(sp);  
    	}
        System.debug('WorkOrderPerformanceController==>'+ msg);

    }





    public void addMeta(Map<String,List<WorkOrderTeam__c>> tMap ,String key,WorkOrderTeam__c wt ){
    	List<WorkOrderTeam__c> tl = tMap.get(key);
    	if(tl == null )tl = new List<WorkOrderTeam__c> ();
    	tl.add(wt);
    	tMap.put(key, tl);
    }

}